import cv2
import numpy as np
def Lzip(mag_spec_sorted, gray, keep):
    thresh = mag_spec_sorted[int((1 - keep) * gray.size)]  # 计算位置的振幅阈值

    mask = mag_spec > thresh
    fCoef_compressed = fCoef * mask
    gray_cp = np.fft.ifft2(fCoef_compressed).real
    return gray_cp

cap = cv2.VideoCapture('D:/bike.mp4')
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        print("没有内容，退出啦 :) ")
        break
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    fCoef = np.fft.fft2(gray)
    mag_spec = np.abs(fCoef)
    mag_spec_sorted = np.sort(mag_spec.ravel())
    gray_1 = Lzip(mag_spec_sorted, gray, 0.5)
    gray_1 = cv2.cvtColor(np.uint8(gray_1), cv2.COLOR_GRAY2BGR)  # type: ignore
    gray_2 = Lzip(mag_spec_sorted, gray, 0.1)
    gray_2 = cv2.cvtColor(np.uint8(gray_2), cv2.COLOR_GRAY2BGR)  # type: ignore

    # 4.显示原视频及其对应的灰度图
    cv2.imshow('original', gray)
    cv2.imshow('0.5', gray_1)
    cv2.imshow('0.1', gray_2)

    # 每隔 1ms 检查一次用户输入，如果按下 'q' 键，退出循环
    if cv2.waitKey(24) == ord('q'):
        break

# 释放视频捕捉资源
cap.release()
# 关闭所有的 GUI 窗口
cv2.destroyAllWindows()